<?php

class JsonDatabase {
    private $filePath;

    public function __construct($filePath) {
        $this->filePath = $filePath;
        // 如果文件不存在，初始化数据库
        if (!file_exists($this->filePath)) {
            $this->initializeDatabase();
        }
    }

    // 初始化数据库
    private function initializeDatabase() {
        $initialData = [
            "code" => 200,
            "message" => "success",
            "data" => [],
            "banner" => []
        ];
        $this->writeJson($initialData);
    }

    // 读取 JSON 文件
    private function readJson() {
        if (!file_exists($this->filePath)) {
            return ['code' => 404, 'message' => 'File not found', 'data' => [], 'banner' => []];
        }
        $json = file_get_contents($this->filePath);
        return json_decode($json, true);
    }

    // 写入 JSON 文件
    private function writeJson($data) {
        if (file_put_contents($this->filePath, json_encode($data, JSON_UNESCAPED_UNICODE))) {
            return ['code' => 200, 'message' => 'success'];
        } else {
            return ['code' => 500, 'message' => 'failed to write file'];
        }
    }

    // 查询所有数据
    public function getAll() {
        $data = $this->readJson();
        return $data;
    }

    // 根据 ID 查询数据
    public function getById($id) {
        $data = $this->readJson();
        foreach ($data['data'] as $item) {
            if ($item['id'] == $id) {
                return ['code' => 200, 'message' => 'success', 'data' => $item];
            }
        }
        return ['code' => 404, 'message' => 'failed: item not found'];
    }

    // 添加数据
    public function add($item) {
        $data = $this->readJson();
        // 检查 title 是否已存在
        foreach ($data['data'] as $existingItem) {
            if ($existingItem['title'] == $item['title']) {
                return ['code' => 400, 'message' => 'failed: data with this title already exists'];
            }
        }
        // 如果 title 不存在，添加新数据
        $item['id'] = count($data['data']) + 1; // 自动生成 ID
        // 如果 jis 为 true，确保 list 字段存在
        if (isset($item['jis']) && $item['jis'] === 'true' && !isset($item['list'])) {
            $item['list'] = [];
        }
        $data['data'][] = $item;
        $result = $this->writeJson($data);
        if ($result['code'] == 200) {
            return ['code' => 200, 'message' => 'success', 'data' => $item];
        } else {
            return ['code' => 500, 'message' => 'failed to add item'];
        }
    }

    // 更新数据（支持多个字段同时更新）
    public function update($id, $newData) {
        $data = $this->readJson();
        foreach ($data['data'] as &$item) {
            if ($item['id'] == $id) {
                // 检查 jis 字段是否发生变化
                if (isset($newData['jis'])) {
                    if ($newData['jis'] === 'true' && (!isset($item['jis']) || $item['jis'] === 'false')) {
                        // 如果 jis 从 false 改为 true，添加 list 字段
                        $item['list'] = []; // 显式初始化 list 字段
                    } elseif ($newData['jis'] === 'false' && isset($item['jis']) && $item['jis'] === 'true') {
                        // 如果 jis 从 true 改为 false，删除 list 字段
                        unset($item['list']);
                    }
                }
                // 合并更新数据
                $item = array_merge($item, $newData);
                $result = $this->writeJson($data);
                if ($result['code'] == 200) {
                    return ['code' => 200, 'message' => 'success', 'data' => $item];
                } else {
                    return ['code' => 500, 'message' => 'failed to update item'];
                }
            }
        }
        return ['code' => 404, 'message' => 'failed: item not found'];
    }

    // 删除数据
    public function delete($id) {
        $data = $this->readJson();
        foreach ($data['data'] as $key => $item) {
            if ($item['id'] == $id) {
                unset($data['data'][$key]);
                $data['data'] = array_values($data['data']); // 重新索引数组
                $result = $this->writeJson($data);
                if ($result['code'] == 200) {
                    return ['code' => 200, 'message' => 'success'];
                } else {
                    return ['code' => 500, 'message' => 'failed to delete item'];
                }
            }
        }
        return ['code' => 404, 'message' => 'failed: item not found'];
    }

    // 添加 banner
    public function addBanner($banner) {
        $data = $this->readJson();
        $banner['id'] = count($data['banner']) + 1;
        $data['banner'][] = $banner;
        $result = $this->writeJson($data);
        if ($result['code'] == 200) {
            return ['code' => 200, 'message' => 'success', 'data' => $banner];
        } else {
            return ['code' => 500, 'message' => 'failed to add banner'];
        }
    }

    // 删除 banner（通过 id）
    public function deleteBanner($id) {
        $data = $this->readJson();
        foreach ($data['banner'] as $key => $banner) {
            if ($banner['id'] == $id) {
                unset($data['banner'][$key]);
                $data['banner'] = array_values($data['banner']); // 重新索引数组
                $result = $this->writeJson($data);
                if ($result['code'] == 200) {
                    return ['code' => 200, 'message' => 'success'];
                } else {
                    return ['code' => 500, 'message' => 'failed to delete banner'];
                }
            }
        }
        return ['code' => 404, 'message' => 'failed: banner not found'];
    }

    // 添加最新一集
    public function addEpisode($id, $episode) {
        $data = $this->readJson();
        foreach ($data['data'] as &$item) {
            if ($item['id'] == $id) {
                // 确保 jis 为 true
                if (!isset($item['jis']) || $item['jis'] !== 'true') {
                    return ['code' => 400, 'message' => 'failed: item does not support episodes'];
                }
                // 检查集的 title 是否已存在
                if (isset($item['list'])) {
                    foreach ($item['list'] as $existingEpisode) {
                        if ($existingEpisode['title'] == $episode['title']) {
                            return ['code' => 400, 'message' => 'failed: episode with this title already exists'];
                        }
                    }
                }
                // 自动生成集数 ID
                $episode['id'] = count($item['list']) + 1;
                $item['list'][] = $episode;
                $result = $this->writeJson($data);
                if ($result['code'] == 200) {
                    return ['code' => 200, 'message' => 'success', 'data' => $episode];
                } else {
                    return ['code' => 500, 'message' => 'failed to add episode'];
                }
            }
        }
        return ['code' => 404, 'message' => 'failed: item not found'];
    }

    // 删除指定集数
    public function deleteEpisode($id, $episodeId) {
        $data = $this->readJson();
        foreach ($data['data'] as &$item) {
            if ($item['id'] == $id) {
                // 确保 jis 为 true
                if (!isset($item['jis']) || $item['jis'] !== 'true') {
                    return ['code' => 400, 'message' => 'failed: item does not support episodes'];
                }
                // 查找并删除指定集数
                foreach ($item['list'] as $key => $episode) {
                    if ($episode['id'] == $episodeId) {
                        unset($item['list'][$key]);
                        $item['list'] = array_values($item['list']); // 重新索引数组
                        $result = $this->writeJson($data);
                        if ($result['code'] == 200) {
                            return ['code' => 200, 'message' => 'success'];
                        } else {
                            return ['code' => 500, 'message' => 'failed to delete episode'];
                        }
                    }
                }
                return ['code' => 404, 'message' => 'failed: episode not found'];
            }
        }
        return ['code' => 404, 'message' => 'failed: item not found'];
    }
}


// 设置响应头为 JSON
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$value = $_REQUEST;
$dbType = $value['dbType'];
$title = $value['title'];
$cover = $value['cover'];
$video = $value['video'];
$jis = $value['jis'];
$path = $value['path'];
$link = $value['link'];
$id = $value['id'];
$jisID = $value['jisID'];
$upd = $value['upd'];
$nr = $value['nr'];

if ($dbType == '' || $dbType == null) {
    echo json_encode(['code' => 400, 'message' => 'failed: dbType is empty']);
    exit();
}

// 进行数据初始化
$db = new JsonDatabase('List.json');

if ($dbType == 'getAll') {
    $allData = $db->getAll();
    echo json_encode($allData, JSON_PRETTY_PRINT);
}

if ($dbType == 'getID') {
    $item = $db->getById($id);
    echo json_encode($item, JSON_PRETTY_PRINT);
}

if ($dbType == 'addItem') {
    $newItem = '';
    if ($jis == 'true') {
        $newItem = [
            'title' => $title,
            'cover' => $cover,
            'video' => $video,
            'jis' => $jis, // 有集数列表
            'list' => [
                [
                    'id' => 1,
                    'title' => '第一集',
                    'video' => $video
                ]
            ]
        ];
    } else {
        $newItem = [
            'title' => $title,
            'cover' => $cover,
            'video' => $video,
            'jis' => $jis, // 有集数列表
        ];
    }
    $addedItem = $db->add($newItem);
    echo json_encode($addedItem, JSON_UNESCAPED_UNICODE);
}

if ($dbType == 'addJIS') {
    $newEpisode = [
        'title' => $title,
        'video' => $video
    ];
    $addedEpisode = $db->addEpisode($id, $newEpisode);
    echo json_encode($addedEpisode, JSON_UNESCAPED_UNICODE);
}

if ($dbType == 'delItem') {
    $deleted = $db->delete($id);
    echo json_encode($deleted, JSON_UNESCAPED_UNICODE);
}

if ($dbType == 'delJIS') {
    $deletedEpisode = $db->deleteEpisode($id, $jisID); // 删除 ID 为 1 的集数
    echo json_encode($deletedEpisode, JSON_UNESCAPED_UNICODE);
}

if ($dbType == 'update') {
    $updatedItem = $db->update($id, [$upd => $nr]);
    echo json_encode($updatedItem, JSON_UNESCAPED_UNICODE);
}

if ($dbType == 'addBanner') {
    $newBanner = [
        'path' => $path,
        'title' => $title,
        'link' => $link
    ];
    $addedBanner = $db->addBanner($newBanner);
    echo json_encode($addedBanner, JSON_UNESCAPED_UNICODE);
}

if ($dbType == 'delBanner') {
    $deletedBanner = $db->deleteBanner($id);
    echo json_encode($deletedBanner, JSON_UNESCAPED_UNICODE);
}
